//
//  QRcodeViewController.m
//  HGMMT
//
//  Created by eport_user1 on 2018/4/9.
//  Copyright © 2018年 eport_user1. All rights reserved.
//

#import "QRcodeViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "UINavigationBar+Awesome.h"
#import <Masonry.h>

#define KQRCodeSize     260

#define kScreenHeight  [UIScreen mainScreen].bounds.size.height
#define kScreenWidth [UIScreen mainScreen].bounds.size.width


@interface QRcodeViewController ()<AVCaptureMetadataOutputObjectsDelegate>{
    NSTimer *_timer;
    BOOL _upOrDown;
}

@property (nonatomic, strong) UIView *scanRectView;
// 硬件设备
@property (strong, nonatomic) AVCaptureDevice            *device;
//输入设备
@property (strong, nonatomic) AVCaptureDeviceInput       *input;
//输出设备
@property (strong, nonatomic) AVCaptureMetadataOutput    *output;
//桥梁.连接输入和输出设备,
@property (strong, nonatomic) AVCaptureSession           *session;
@property (strong, nonatomic) AVCaptureVideoPreviewLayer *preview;

//添加扫面框样式
@property(nonatomic,strong)UIImageView *centerView; //中间的扫描视图
@property(nonatomic,strong)UIImageView  *scanView; //扫描线

@property(nonatomic,assign)int num;

@property(nonatomic,strong)UILabel *scanLabel;


@end

@implementation QRcodeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    
   
    
    _num = 0;
    _upOrDown = NO;
    
    //1初始化导航栏
    [self _initNav];
    
    //判断软件有没有开启,相机权限
    self.device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    self.input = [AVCaptureDeviceInput deviceInputWithDevice:self.device error:nil];
    
    if (self.input)
    {
        
        //2.初始化视图
        [self _initView];
        
        //3.开始捕获
        [self startCatchIt];
        
    }
    else
    {
        
        self.view.backgroundColor = [UIColor blackColor];
        
        UIAlertController *alterVC = [UIAlertController alertControllerWithTitle:@"未获得授权使用摄像头" message:@"请在iOS“设置”-“隐私”-“相机”中打开" preferredStyle:UIAlertControllerStyleAlert];
        
        [alterVC addAction:[UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            
            [self.navigationController popViewControllerAnimated:YES];
        }]];
        
        [self presentViewController:alterVC animated:YES completion:nil];
        
        
        
    }
    
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



//初始化导航栏
-(void)_initNav{
    
    
    self.title = @"扫描二维码";
    
    self.view.backgroundColor = [UIColor clearColor];
   
    
}


-(void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    
   // self.navigationController.navigationBar.hidden = NO;
    
    
    _num = 0;
    _upOrDown = NO;
    
    if (self.session != nil) {
        
        [self.session startRunning];
    }
    
    UIColor *color = [UIColor blackColor];
    [self.navigationController.navigationBar lt_setBackgroundColor:[color colorWithAlphaComponent:0.5]];
    
    
    [self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.shadowImage = [[UIImage alloc] init];
    
    [self.navigationController.navigationBar setTitleTextAttributes:
     
     @{NSFontAttributeName:[UIFont systemFontOfSize:18],
       
       NSForegroundColorAttributeName:[UIColor cyanColor]}];
    
    
}


-(void)viewWillDisappear:(BOOL)animated{
    
    [super viewWillDisappear:animated];
    
    //导航栏字体
    [self.navigationController.navigationBar setTitleTextAttributes:
     
     @{NSFontAttributeName:[UIFont systemFontOfSize:18],
       
       NSForegroundColorAttributeName:[UIColor blackColor]}];
    
    [self.session stopRunning];

    
    
   
    UIColor *color = [UIColor blackColor];
    [self.navigationController.navigationBar lt_setBackgroundColor:[color colorWithAlphaComponent:1]];
    [self.navigationController.navigationBar lt_reset];
    
    
    [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:nil];
    
    
}

-(void)backBtnAction{
    
    [self.navigationController popViewControllerAnimated:YES];
    
}


- (void)_initView
{
    UIView *topView = ({
        UIView *view = [UIView new];
        view.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
        [self.view addSubview:view];
        view;
    });
    [topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.top.equalTo(self.view).offset(64);
        make.height.equalTo(@((kScreenHeight-64-KQRCodeSize)/2.0 - 74));
    }];
    UIView *leftView = ({
        UIView *view = [UIView new];
        view.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
        [self.view addSubview:view];
        view;
    });
    [leftView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view);
        make.width.equalTo(@((kScreenWidth-KQRCodeSize)/2.0));
        make.top.equalTo(topView.mas_bottom);
        make.height.equalTo(@(KQRCodeSize));
    }];
    UIView *rightView = ({
        UIView *view = [UIView new];
        view.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
        [self.view addSubview:view];
        view;
    });
    [rightView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view);
        make.width.equalTo(@((kScreenWidth-KQRCodeSize)/2.0));
        make.top.equalTo(topView.mas_bottom);
        make.height.equalTo(@(KQRCodeSize));
    }];
    UIView *bottomView = ({
        UIView *view = [UIView new];
        view.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
        [self.view addSubview:view];
        view;
    });
    [bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.top.equalTo(rightView.mas_bottom);
        make.height.equalTo(@((kScreenHeight-64-KQRCodeSize)/2.0+74));
    }];
    _centerView = ({
        UIImageView *imageView = [UIImageView new];
        imageView.image = [UIImage imageNamed:@"scanningFrame"];
        [self.view addSubview:imageView];
        imageView;
    });
    [_centerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(leftView.mas_right);
        make.right.equalTo(rightView.mas_left);
        make.top.equalTo(topView.mas_bottom);
        make.bottom.equalTo(bottomView.mas_top);
    }];
    //设置扫描线
    _scanView = [[UIImageView alloc]init];
    [_scanView setFrame:CGRectMake(0, 10, CGRectGetWidth(_centerView.frame), 2)];
    _scanView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"scanLine"]];
    [_centerView addSubview:_scanView];
    
    
    //
    
    CGFloat Y = (kScreenHeight - KQRCodeSize-64)/2.0+64-74+KQRCodeSize+35;
    _scanLabel = [[UILabel alloc]initWithFrame:CGRectMake(0,Y, kScreenWidth, 12)];
    _scanLabel.font = [UIFont systemFontOfSize:13];
    
    _scanLabel.text = @"请将二维码/条码放入框内,即可自动扫描";
    _scanLabel.textColor = [UIColor whiteColor]; //[Tool colorWithHex:0xffffff alpha:0.5];
    _scanLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:_scanLabel];
    
    
    
}


//开启捕获
-(void)startCatchIt{
    
    CGSize windowSize = [UIScreen mainScreen].bounds.size;
    
    CGSize scanSize = CGSizeMake(KQRCodeSize,KQRCodeSize);
    CGRect scanRect = CGRectMake((windowSize.width-scanSize.width)/2, (windowSize.height-scanSize.height-64)/2.0+64-74, scanSize.width, scanSize.height);
    
    scanRect = CGRectMake(scanRect.origin.y/windowSize.height, scanRect.origin.x/windowSize.width, scanRect.size.height/windowSize.height,scanRect.size.width/windowSize.width);
    
    
    self.output = [[AVCaptureMetadataOutput alloc]init];
    [self.output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    
    self.session = [[AVCaptureSession alloc]init];
    [self.session setSessionPreset:([UIScreen mainScreen].bounds.size.height<500)?AVCaptureSessionPreset640x480:AVCaptureSessionPresetHigh];
    
    [self.session addInput:self.input];
    [self.session addOutput:self.output];
    self.output.metadataObjectTypes=@[AVMetadataObjectTypeQRCode];
    self.output.rectOfInterest = scanRect;
    
    self.preview = [AVCaptureVideoPreviewLayer layerWithSession:self.session];
    self.preview.videoGravity = AVLayerVideoGravityResizeAspectFill;
    self.preview.frame = [UIScreen mainScreen].bounds;
    [self.view.layer insertSublayer:self.preview atIndex:0];
    
    //开始捕获
    [self.session startRunning];
    
    //开启定时器
    _timer = [NSTimer scheduledTimerWithTimeInterval:0.02 target:self selector:@selector(animationEvent) userInfo:nil repeats:YES];
    
    
    
    
    
    
    
}

//定时器
- (void)animationEvent
{
    CGFloat height = CGRectGetHeight(_centerView.frame);
    if (_upOrDown == NO) {
        _num ++;
        _scanView.frame = CGRectMake(0,  _num, CGRectGetWidth(_centerView.frame), 1);
        if (_num == height) {
            _upOrDown = YES;
        }
    }
    else {
        _num --;
        _scanView.frame = CGRectMake(0, _num , CGRectGetWidth(_centerView.frame), 1);
        if (_num == 0) {
            _upOrDown = NO;
        }
    }
}




- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
    __weak QRcodeViewController *weakThis = self;
    
    if ( (metadataObjects.count==0) )
    {
        [self.session startRunning];
        
        return;
    }
    
    if (metadataObjects.count>0) {
        
        [self.session stopRunning];
        
        //扫描完成,播放声音
        
        NSString *voicePath = [[NSBundle mainBundle]pathForResource:@"qrcodedi" ofType:@"wav"];
        NSURL *voiceURL = [NSURL fileURLWithPath:voicePath];
        SystemSoundID soundID = 0;
        AudioServicesCreateSystemSoundID((__bridge CFURLRef)(voiceURL), &soundID);
        //  AudioServicesPlaySystemSound(soundID);
        //播放完成的block
        AudioServicesPlaySystemSoundWithCompletion(soundID, ^{
            
            
            AVMetadataMachineReadableCodeObject *metadataObject = metadataObjects.firstObject;    //获取到的网址
            
            //获取二维码信息结果,字符串形式.
            NSString *resultString = [metadataObject stringValue];
            
                
                //必须回到主线程,刷新UI.扫描结果不是在主线程
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                   // [self.navigationController popViewControllerAnimated:YES];
                    
                    if (self.block) {
                        
                        self.block(resultString);
                        
                        [self.navigationController popViewControllerAnimated:YES];
                    }
                    
                    
                });
            
        });
        
        
        
    }
}





-(void)dealloc{
    
    [_timer invalidate];
    _timer = nil;
    
}






@end
